/***
 * @Author: xbn
 * title: storage.ts
 * Desc: 对存储的简单封装
 */

// 类型 window.localStorage,window.sessionStorage,
type Config = {
  type: any;
  prefix: string;
  expire: any;
  isEncrypt: Boolean;
};
const config: Config = {
  type: "localStorage", // 本地存储类型 sessionStorage
  prefix: 'space', // 名称前缀 建议：项目名 + 项目版本
  expire: 864000, //过期时间 单位：秒
  isEncrypt: false, // 默认加密 为了调试方便, 开发过程中可以不加密
};
 
// 判断是否支持 Storage
export const isSupportStorage = () => {
  return typeof Storage !== "undefined" ? true : false;
};
 
// 设置 setStorage
export const setStorage = (key: string, value: any, expire = 0) => {
  if (value === "" || value === null || value === undefined) {
    value = null;
  }
 
  if (isNaN(expire) || expire < 0) throw new Error("Expire must be a number");
 
  expire = expire ? expire : config.expire;
  let data = {
    value: value, // 存储值
    time: Date.now(), //存值时间戳
    expire: expire, // 过期时间
  };
 
  // console.log("shezhi ", data);
 
  const encryptString = JSON.stringify(data);
 
  (window[config.type] as any).setItem(autoAddPrefix(key), encryptString);
};
 
// 获取 getStorage
export const getStorage = (key: string) => {
  key = autoAddPrefix(key);
  // key 不存在判断
  if (
    !(window[config.type] as any).getItem(key) ||
    JSON.stringify((window[config.type] as any).getItem(key)) === "null"
  ) {
    return null;
  }
 
  // 优化 持续使用中续期
  const storage = JSON.parse((window[config.type] as any).getItem(key));
 
  let nowTime = Date.now();
 
  // 过期删除
 
  let setExpire = (storage.expire || config.expire) * 1000,
    expDiff = nowTime - storage.time;
  // console.log("设置时间", setExpire, expDiff);
  if (setExpire < expDiff) {
    removeStorage(key);
    return null;
  } else {
    // 未过期期间被调用 则自动续期 进行保活
    setStorage(autoRemovePrefix(key), storage.value, storage.expire);
    return storage.value;
  }
};
 
// 是否存在 hasStorage
export const hasStorage = (key: string) => {
  key = autoAddPrefix(key);
  let arr = getStorageAll().filter((item) => {
    return item.key === key;
  });
  return arr.length ? true : false;
};
 
// 获取所有key
export const getStorageKeys = () => {
  let items = getStorageAll();
  let keys = [];
  for (let index = 0; index < items.length; index++) {
    keys.push(items[index].key);
  }
  return keys;
};
 
// 获取全部 getAllStorage
export const getStorageAll = () => {
  let len = window[config.type].length; // 获取长度
  let arr = new Array(); // 定义数据集
  for (let i = 0; i < len; i++) {
    // 获取key 索引从0开始
    let getKey = (window[config.type] as any).key(i);
    // 获取key对应的值
    let getVal = (window[config.type] as any).getItem(getKey);
    // 放进数组
    arr[i] = { key: getKey, val: getVal };
  }
  return arr;
};
 
// 删除 removeStorage
export const removeStorage = (key: string) => {
  (window[config.type] as any).removeItem(autoAddPrefix(key));
};
 
// 清空 clearStorage
export const clearStorage = () => {
  (window[config.type] as any).clear();
};
 
// 名称前自动添加前缀
const autoAddPrefix = (key: string) => {
  const prefix = config.prefix ? config.prefix + "_" : "";
  return prefix + key;
};
 
// 移除已添加的前缀
const autoRemovePrefix = (key: string) => {
  const len: any = config.prefix ? config.prefix.length + 1 : "";
  return key.substr(len);
  // const prefix = config.prefix ? config.prefix + '_' : '';
  // return  prefix + key;
};

export const DateFormat = (date: any, format: string): string => {
  //无参数
  if (date == undefined && format == undefined) {
    date = new Date();
    format = "yyyy-MM-dd HH:mm:ss";
  }
  //无日期
  else if (typeof (date) == "string") {
      format = date;
      date = new Date();
  }
  //无格式化参数
  else if (format === undefined) {
      format = "yyyy-MM-dd HH:mm:ss";
  }
  else { }
  //没有分隔符的特殊处理

  var map = {
      "y": date.getFullYear() + "",//年份
      "M": date.getMonth() + 1 + "", //月份 
      "d": date.getDate() + "", //日 
      "H": date.getHours(), //小时 24
      "m": date.getMinutes() + "", //分 
      "s": date.getSeconds() + "", //秒 
      "q": Math.floor((date.getMonth() + 3) / 3) + "", //季度 
      "f": date.getMilliseconds() + "" //毫秒 
  };
  //小时 12
  // if (map["H"] > 12) { map["h"] = map["H"] - 12 + ""; }
  // else { map["h"] = map["H"] + ""; }
  map["h"] = map["H"] + "";
  map["H"] += "";

  var reg = "yMdHhmsqf";
  var all = "", str = "";
  for (var i = 0, n = 0; i < reg.length; i++) {
      n = format.indexOf(reg[i]);
      if (n < 0) { continue; }
      all = "";
      for (; n < format.length; n++) {
          if (format[n] != reg[i]) {
              break;
          }
          all += reg[i];
      }
      if (all.length > 0) {
          if (all.length == map[reg[i]].length) {
              str = map[reg[i]];
          }
          else if (all.length > map[reg[i]].length) {
              if (reg[i] == "f") {
                  str = map[reg[i]] + charString("0", all.length - map[reg[i]].length);
              }
              else {
                  str = charString("0", all.length - map[reg[i]].length) + map[reg[i]];
              }
          }
          else {
              switch (reg[i]) {
                  case "y": str = map[reg[i]].substr(map[reg[i]].length - all.length); break;
                  case "f": str = map[reg[i]].substr(0, all.length); break;
                  default: str = map[reg[i]]; break;
              }
          }
          format = format.replace(all, str);
      }
  }
  return format;
};

const charString = (char: string, count: number) => {
  var str: string = "";
  while (count--) {
      str += char;
  }
  return str;
}